/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DBServerLogin.java
 *
 * Created on May 17, 2012, 4:50:57 AM
 */
package db.server.GUI;

import db.server.BUS.OptionBUS;
import db.server.DTO.ConfigDTO;
        
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;

/**
 *
 * @author QuangKhai
 */
public final class DBServerLogin extends javax.swing.JFrame {          
    private OptionBUS optionBUS = new OptionBUS();
    public static ConfigDTO config = new ConfigDTO();
    
    public static String pathWorkSpace = "";
    private String pathSystem = "";
    private boolean check = false;
    public static DBServerStart dbServerStart;
    
    /** Creates new form DBServerLogin */
    public DBServerLogin() throws IOException {
        initComponents(); 
        
        ImageIcon icon = new ImageIcon(getClass().getResource("/image/loginScreen.png"));
        this.setIconImage(icon.getImage());
        
        try {
            Thread.sleep(5000);
            DBServerLogin.dbServerStart.dispose();
        } catch (InterruptedException ex) {
            Logger.getLogger(DBServerStart.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.pathSystem = "C:\\ServerConfig";
        
        File configFile = new File(pathSystem);
        if(configFile.exists()){
            showConfig(); 
            check = true;
            lb_title.setText("Login");
        }else{            
            tf_workspace.setText("C:\\DB-Server");
            check = false;
            tf_retypepassword.setEnabled(true);
            lb_title.setText("Sign Up");
        }  
        
        this.setSize(this.getWidth(), this.getHeight());
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((d.width - this.getWidth()) / 2, (d.height - this.getHeight()) / 2);
    }

    public void showConfig(){
        config = optionBUS.readConfigFile(pathSystem);        
        
        if(config.getCheck().compareTo("true") == 0){
            tf_username.setText(config.getUsername());
            tf_password.setText(config.getPassword());
            ck_rememberpassword.setSelected(true);
            check = true;
        }else{
            check = false;
        }
        
        tf_retypepassword.setEnabled(false);
        tf_workspace.setText(config.getWorkspace());
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lb_title = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();
        tf_username = new javax.swing.JTextField();
        tf_password = new javax.swing.JPasswordField();
        ck_rememberpassword = new javax.swing.JCheckBox();
        bt_connect = new javax.swing.JButton();
        bt_cancel = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        tf_workspace = new javax.swing.JTextField();
        bt_openworkspace = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        tf_retypepassword = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        tf_address = new javax.swing.JTextField();
        tf_port = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel1.setText("Username");

        jLabel2.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel2.setText("Password");

        jLabel3.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel3.setText("Workspace");

        lb_title.setFont(new java.awt.Font("Cambria", 1, 14)); // NOI18N
        lb_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lb_title.setText("Login");

        jSeparator1.setRequestFocusEnabled(false);
        jSeparator1.setVerifyInputWhenFocusTarget(false);

        jLabel5.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel5.setText("Infomation");

        tf_username.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        tf_username.setText(".");

        tf_password.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N

        ck_rememberpassword.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        ck_rememberpassword.setText("Remember password");

        bt_connect.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        bt_connect.setText("Connect");
        bt_connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_connectActionPerformed(evt);
            }
        });

        bt_cancel.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        bt_cancel.setText("Cancel");
        bt_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_cancelActionPerformed(evt);
            }
        });

        tf_workspace.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        tf_workspace.setText("D:\\\\DB-Server");

        bt_openworkspace.setText("...");
        bt_openworkspace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_openworkspaceActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel6.setText("Retype");

        tf_retypepassword.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N

        jLabel4.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel4.setText("IP Address");

        jLabel7.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        jLabel7.setText("Port");

        tf_address.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        tf_address.setText("127.0.0.1");

        tf_port.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        tf_port.setText("3200");

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/login.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lb_title))
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7)
                            .addComponent(jLabel4))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tf_address)
                            .addComponent(tf_retypepassword)
                            .addComponent(tf_password)
                            .addComponent(tf_username, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                            .addComponent(ck_rememberpassword)
                            .addComponent(tf_port))))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(64, Short.MAX_VALUE)
                .addComponent(bt_connect, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(bt_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(57, 57, 57))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_workspace, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_openworkspace, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 291, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lb_title, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tf_username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tf_password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tf_retypepassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ck_rememberpassword)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_connect)
                    .addComponent(bt_cancel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tf_workspace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt_openworkspace, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void bt_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_connectActionPerformed
// TODO add your handling code here:    
    if(!check){
        if(tf_password.getText().compareTo(tf_retypepassword.getText()) == 0){
            config.setPassword(tf_password.getText());
            config.setUsername(tf_username.getText());
            config.setWorkspace(tf_workspace.getText());
            config.setAddress(tf_address.getText());
            config.setPort(tf_port.getText());

            if(ck_rememberpassword.isSelected()){
                config.setCheck("true");
            }else{
                config.setCheck("false");
            }

            DBServerLogin.pathWorkSpace = tf_workspace.getText();
            DBServer.main(null);
            
            try {
                optionBUS.saveConfig(config, pathSystem);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(DBServerLogin.class.getName()).log(Level.SEVERE, null, ex);
            }

            dispose();
        }else{
            JOptionPane.showMessageDialog(null, "Retype password not correct! Please retype carefully!");
            tf_password.setText("");
            tf_retypepassword.setText("");
        }
    }else{
        if(tf_password.getText().compareTo(config.getPassword()) == 0 && tf_username.getText().compareTo(config.getUsername()) == 0){            
            config.setCheck(ck_rememberpassword.isSelected() + "");
            config.setWorkspace(tf_workspace.getText());
            DBServerLogin.pathWorkSpace = tf_workspace.getText();
            DBServer.main(null);  
            
            try {
                optionBUS.saveConfig(config, pathSystem);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(DBServerLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            
            dispose();
        }else{
            JOptionPane.showMessageDialog(null, "Login failed! Please try again with exactly info!");
            tf_password.setText("");
            tf_username.setText("");
        }
    }
}//GEN-LAST:event_bt_connectActionPerformed

private void bt_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cancelActionPerformed
// TODO add your handling code here:
    dispose();
}//GEN-LAST:event_bt_cancelActionPerformed

private void bt_openworkspaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_openworkspaceActionPerformed
// TODO add your handling code here:
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fc.setAcceptAllFileFilterUsed(false);

    int returnVal = fc.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {            
        pathWorkSpace = fc.getSelectedFile().toString() + "\\DB-Server";
        
        tf_workspace.setText(pathWorkSpace);
        tf_workspace.setToolTipText(pathWorkSpace);
    }        
}//GEN-LAST:event_bt_openworkspaceActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DBServerLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DBServerLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DBServerLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DBServerLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new DBServerLogin().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(DBServerLogin.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_cancel;
    private javax.swing.JButton bt_connect;
    private javax.swing.JButton bt_openworkspace;
    private javax.swing.JCheckBox ck_rememberpassword;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lb_title;
    private javax.swing.JTextField tf_address;
    private javax.swing.JPasswordField tf_password;
    private javax.swing.JTextField tf_port;
    private javax.swing.JPasswordField tf_retypepassword;
    private javax.swing.JTextField tf_username;
    private javax.swing.JTextField tf_workspace;
    // End of variables declaration//GEN-END:variables
}
